angular.module('charity.message',[])
    .controller('messageCtr', ['$scope', '$filter', 'messageService', '$routeParams', '$uibModal','logger',
        function ($scope, $filter, messageService, $routeParams,$uibModal, logger) {
            $scope.stores = [];
            $scope.searchKeywords = '';
            $scope.filteredStores = [];
            $scope.row = '',

            $scope.select = function (page) {
                var end, start;
                start = (page - 1) * $scope.numPerPage;
                end = start + $scope.numPerPage;
                return $scope.currentPageStores = $scope.filteredStores.slice(start, end);
            };

            $scope.onFilterChange = function () {
                $scope.select(1);
                $scope.currentPage = 1;
                return $scope.row = '';
            };

            $scope.onNumPerPageChange = function () {
                $scope.select(1);
                return $scope.currentPage = 1;
            };

            $scope.onOrderChange = function () {
                $scope.select(1);
                return $scope.currentPage = 1;
            };

            $scope.search = function () {
                messageService.queryAllMessages().then(function (results) {
                    if(!results || results.code != 0){
                        logger.logError((results && results.message) || '查询数据失败,请重新登录');
                        return;
                    }
                    $scope.stores = results.data || [];

                    $scope.filteredStores = $filter('filter')($scope.stores, $scope.searchKeywords);
                    return $scope.onFilterChange();
                });
            };

            $scope.order = function (rowName) {
                if ($scope.row === rowName) {
                    return;
                }
                $scope.row = rowName;
                $scope.filteredStores = $filter('orderBy')($scope.stores, rowName);
                return $scope.onOrderChange();
            };
            $scope.numPerPageOpt = [3, 5, 10, 20];
            $scope.numPerPage = $scope.numPerPageOpt[2];
            $scope.currentPage = 1;
            $scope.currentPageStores = [];

            var init = function () {
                $scope.search();
            };
            init();
        }])

    .factory('messageService', ['$http', function ($http) {
        return {
            queryAllMessages: function () {
                return $http({
                    method: "GET",
                    url: "/management/messages"
                }).then(function (results) {
                    return results.data;
                })
            }
        }
    }]);